package org.yunai.swjg.server.module.player.template;

import org.jumpmind.symmetric.csv.CsvReader;
import org.yunai.yfserver.util.Assert;
import org.yunai.yfserver.util.CsvUtil;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 声望模版
 * User: yunai
 * Date: 13-5-30
 * Time: 下午7:26
 */
public class ReputationTemplate {

    /**
     * 声望等级<br />
     * 声望范围为[{@link #reputationStart}, {@link #reputationEnd});
     */
    private short level;
    /**
     * 声望开始
     */
    private int reputationStart;
    /**
     * 声望结束<br />
     * 默认最高等级的上限为{@link Integer#MAX_VALUE}
     */
    private int reputationEnd;

    public short getLevel() {
        return level;
    }

    public int getReputationStart() {
        return reputationStart;
    }

    public int getReputationEnd() {
        return reputationEnd;
    }

    // ==================== 非set/get方法 ====================
    private static Map<Short, ReputationTemplate> templates = new HashMap<>();

    public static ReputationTemplate get(short level) {
        return templates.get(level);
    }

    public static ReputationTemplate getByReputation(int reputation) {
        Assert.isTrue(reputation >= 0, "声望必须大于等于0.");
        for (ReputationTemplate template : templates.values()) {
            if (reputation >= template.getReputationStart()
                    && reputation < template.getReputationEnd()) {
                return template;
            }
        }
        throw new IllegalArgumentException("该情况是不会发生的！");
    }

    public static int size() {
        return templates.size();
    }

    public static void load() {
        CsvReader reader = null;
        // 声望模版
        templates = new HashMap<>();
        try {
            reader = CsvUtil.createReader("csv/player/reputation_template.csv");
            reader.readHeaders();
            while (reader.readRecord()) {
                ReputationTemplate template = genPartnerTemplate(reader);
                templates.put(template.level, template);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
        // 设置声望上限
        for (Map.Entry<Short, ReputationTemplate> entry : templates.entrySet()) {
            ReputationTemplate nextTemplate = templates.get((short) (entry.getKey() + 1));
            entry.getValue().reputationEnd = nextTemplate != null ? nextTemplate.reputationStart : Integer.MAX_VALUE;
        }
    }

    private static ReputationTemplate genPartnerTemplate(CsvReader reader) throws IOException {
        ReputationTemplate template = new ReputationTemplate();
        template.level = CsvUtil.getShort(reader, "level", (short) 0);
        template.reputationStart = CsvUtil.getInt(reader, "reputationStart", 0);
        return template;
    }
}
